package callabelAndFuture;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFuture {

	public static void main(String[] args) throws InterruptedException, ExecutionException{
		//callable and future
		ExecutorService service=Executors.newSingleThreadExecutor();
		Future<String> future=service.submit(new Callable<String>() {

			public String call() throws Exception {
				// TODO Auto-generated method stub
				String string="hello";
				Thread.sleep(2000);
				return string;
			}
		});
		System.out.println("wait the result");
		String result=future.get();
		System.out.println("Result is "+result);
		System.out.println();
		System.out.println("****************************************");
		System.out.println();
		//completion service
		ExecutorService service2=Executors.newFixedThreadPool(10);
		CompletionService<String> completionService=new ExecutorCompletionService<String>(service2);
		for(int i=0;i<10;i++){
			completionService.submit(new Callable<String>() {

				public String call() throws Exception {
					// TODO Auto-generated method stub
					Thread.sleep(new Random().nextInt(500));
					return Thread.currentThread().getName();
				}
			});
		}
		
		for(int i=0;i<10;i++){
			String result2=completionService.take().get();
			System.out.println("The result of completion is "+result2);
		}
	}
}
